package com.mhc.suzuki.service.impl;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.mhc.suzuki.constant.AnnexConstant;
import com.mhc.suzuki.constant.CustomerTypeEnum;
import com.mhc.suzuki.constant.DirConfig;
import com.mhc.suzuki.dal.model.CustomerDO;
import com.mhc.suzuki.dal.model.OrderCustomerRelDO;
import com.mhc.suzuki.dal.model.OrderDO;
import com.mhc.suzuki.dal.query.OrderCustomerRelQuery;
import com.mhc.suzuki.dal.query.OrderQuery;
import com.mhc.suzuki.manager.CreditQueryApplyManager;
import com.mhc.suzuki.manager.CustomerManager;
import com.mhc.suzuki.manager.OrderCustomerRelManager;
import com.mhc.suzuki.manager.OrderManager;
import com.mhc.suzuki.service.AnnexListService;
import com.mhc.suzuki.service.DownloadService;
import com.mhc.suzuki.service.OssService;
import com.mhc.suzuki.util.CompressedFileUtil;
import com.mhc.suzuki.util.DateUtil;
import com.mhc.suzuki.util.ExcelUtil;
import com.mhc.suzuki.vo.AnnexListVO;
import com.mhc.suzuki.vo.CreditExcelVO;
import com.mhc.suzuki.vo.DownloadFileInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class DownloadServiceImpl implements DownloadService {

    @Autowired
    private DirConfig dirConfig;
    @Autowired
    private AnnexListService annexListService;
    @Autowired
    private OssService ossService;
    @Autowired
    private OrderManager orderManager;
    @Autowired
    private CreditQueryApplyManager creditQueryApplyManager;
    @Autowired
    private OrderCustomerRelManager orderCustomerRelManager;
    @Autowired
    private CustomerManager customerManager;

    private static final String FILE_NAME = "征信列表.xlsx";

    /**
     * excel column formate:column_#_width_#_, excel中每一列的名称
     *
     */
    private static final String[] USER_RECORES_COLUMNS = new String[]{
            "序号_#_1000_#_",
            "查询日期_#_3000_#_",
            "征信角色_#_3000_#_",
            "客户姓名_#_3000_#_",
            "身份证号_#_3000_#_",
            "业务部门_#_3000_#_",
            "业务员_#_3000_#_",
            "汽车贷款_#_3000_#_YELLOW",
            "是否取得客户书面授权_#_3000_#_YELLOW",
            "授权资料是否齐全_#_3000_#_YELLOW",
            "是否贷款_#_3000_#_YELLOW",
            "提交机构名称_#_3000_#_YELLOW",
            "提交人_#_3000",
            "备注_#_15000_#_BLUE"
    };

    /**
     * *the column will display on xls files. must the same as the entity fields.对应上面的字段.
     */
    private static final String[] USER_RECORES_FIELDS = new String[]{
            "id", "queryDate", "customerTypeName", "customerName", "idCard", "deptName", "staffName", "carLoan",
            "writtenAuthorization", "completeInformation", "isLoan", "commitOrganization", "commitName", "remark"
    };

    @Override
    public DownloadFileInfoVO downloadFile(List<String> orderNOList, String userName) throws Exception {
        String now = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
        String dir = dirConfig.getTmpDir() + now + "/";
        String zipDir = dirConfig.getZipTmpDir() + now + "/";
        List<CreditExcelVO> creditExcelVOList = creditQueryApplyManager.selectByOrderNOList(orderNOList);

        for (CreditExcelVO creditExcelVO : creditExcelVOList) {
            FileUtils.forceMkdir(new File(dir));
            String fileName = dir + creditExcelVO.getCustomerName() +
                    creditExcelVO.getIdCard().substring(creditExcelVO.getIdCard().length() - 4) + ".pdf";
            this.createCreditAnnexPDF(creditExcelVO.getOrderNo(), fileName);
        }
        this.createCreditListExcel(dir, creditExcelVOList, userName);
        CompressedFileUtil compressedFileUtil = new CompressedFileUtil();
        String targetName = compressedFileUtil.compressedFile(dir, zipDir);
        File file = new File(zipDir + "/" + targetName);
        return new DownloadFileInfoVO(targetName, file);
    }


    private void createCreditListExcel(String dir, List<CreditExcelVO> creditExcelVOList, String userName) throws Exception {
        String bankName = "";
        int i = 0;
        for (CreditExcelVO creditExcelVO : creditExcelVOList) {
            i++;
            creditExcelVO.setId(i);
            creditExcelVO.setQueryDate(DateUtil.getNowTime("yyyyMMdd"));
            creditExcelVO.setCustomerTypeName(CustomerTypeEnum.getCustomerTypeEnum(creditExcelVO.getCustomerType()).getName());
            //提交人,取当前用户,银行驻点员
            creditExcelVO.setCommitName(userName);
            bankName = creditExcelVO.getBankName();
            OrderCustomerRelQuery orderCustomerRelQuery = new OrderCustomerRelQuery();
            orderCustomerRelQuery.setOrderByClause("customer_type asc");
            //经过排序,确保购车人放在前面
            orderCustomerRelQuery.createCriteria().andOrderNoEqualTo(creditExcelVO.getOrderNo()).andIsDeletedEqualTo(0);
            List<OrderCustomerRelDO> orderCustomerRelDOList = orderCustomerRelManager.selectByQuery(orderCustomerRelQuery);
            if (orderCustomerRelDOList != null && orderCustomerRelDOList.size() > 0) {
                String remark = "";
                for (OrderCustomerRelDO orderCustomerRelDO : orderCustomerRelDOList) {
                    if (orderCustomerRelDO.getOrderNo().equals(creditExcelVO.getOrderNo())) {
                        //共同购车人或者担保人,需要在备注中加上购车人的姓名和身份证
                        if (CustomerTypeEnum.BUYER.getCode().equals(orderCustomerRelDO.getCustomerType())) {
                            CustomerDO customerDO = customerManager.selectByPrimaryKey(orderCustomerRelDO.getCustomerId());
                            remark = "主贷人:" + customerDO.getCustomerName() + ", 身份证号码:" + customerDO.getIdCard();
                        } else if (CustomerTypeEnum.COMMONBUYER.getCode().equals(orderCustomerRelDO.getCustomerType()) || CustomerTypeEnum.SPONSOR.getCode().equals(orderCustomerRelDO.getCustomerType())) {
                            creditExcelVO.setRemark(remark);
                        }
                    }
                }
            }
            if (CustomerTypeEnum.BUYER.getCode().equals(creditExcelVO.getCustomerType())) {
                creditExcelVO.setRemark("");
            }
        }

        XSSFWorkbook workbook = new XSSFWorkbook();
        ExcelUtil<CreditExcelVO> userSheet = new ExcelUtil<>();
        userSheet.creatAuditSheet(workbook, bankName,
                creditExcelVOList, USER_RECORES_COLUMNS, USER_RECORES_FIELDS);
        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(dir + FILE_NAME);
            workbook.write(fileOut);
        } catch (IOException e) {
            log.error("IOException", e);
        } finally {
            if (fileOut != null) {
                fileOut.close();
            }
        }
    }

    private void createCreditAnnexPDF(String orderNO, String fileName) throws Exception {

        //创建文件
        Document document = new Document();
        //建立一个书写器
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        //打开文件
        document.open();
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.createCriteria().andOrderNoEqualTo(orderNO);
        String annexBatchNo = "";
        List<OrderDO> orderDOList = orderManager.selectByQuery(orderQuery);
        if (orderDOList != null && orderDOList.size() > 0) {
            annexBatchNo = orderDOList.get(0).getAnnexBatchNo();
        }
        List<AnnexListVO> annexListVOList = annexListService.getAnnexList(annexBatchNo, AnnexConstant.ANNEX_TYPE_CREDIT);
        if (annexListVOList != null && annexListVOList.size() > 0) {
            annexListVOList.forEach(annexListVO -> {
                try {
                    //todo 加上压缩
                    String url = ossService.getUrl(annexListVO.getAnnexGroup(), annexListVO.getAnnexUrl()+AnnexConstant.COMPRESS_W400H400);
                    Image image = Image.getInstance(new URL(url));
                    image.scaleAbsolute(500, 500);
                    document.add(image);
                } catch (DocumentException e) {
                    log.error("DocumentException", e);
                } catch (IOException e) {
                    log.error("IOException", e);
                }

            });
        } else {
            document.add(new Paragraph("no images ~"));
        }
        //关闭文档
        document.close();
        //关闭书写器
        writer.close();
    }
}
